from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse

from main.models import Article
from user.models import CustomUser
from .forms import CommentForm
from .models import Collect,Comment
import json

# Create your views here.


def collect(request):
    a_id = request.POST.get("article")
    u_id = request.POST.get("user")
    user = get_object_or_404(CustomUser, id=u_id)
    article = get_object_or_404(Article, id=a_id)

    collect = Collect.objects.filter(user=user, article=article).first()
    if collect is None:
        Collect.objects.create(user=user, article=article)
        return JsonResponse({'code':0, 'status': 'success', 'msg':'收藏成功'})
    else:
        collect.delete()
        return JsonResponse({'code':0, 'status': 'success', 'msg':'取消收藏成功'})

from django.contrib.auth.decorators import login_required

def delete_comment(request):
    # 添加登录验证
    if not request.user.is_authenticated:
        return JsonResponse({
            "code": -1001,
            "msg": "请先登录",
        })
        
    if request.method == "POST":
        comment_id = request.POST.get("comment_id")
        try:
            comment = Comment.objects.get(id=comment_id)
            # 添加权限验证，确保用户只能删除自己的评论
            if comment.user == request.user:
                # 如果是父评论，删除所有回复
                if comment.get_replays().exists():
                    comment.get_replays().delete()
                # 删除评论本身
                comment.delete()
                return JsonResponse({
                    "code": 0,
                    "msg": "删除成功",
                })
            else:
                return JsonResponse({
                    "code": -1003,
                    "msg": "无权限删除此评论",
                })
        except Comment.DoesNotExist:
            return JsonResponse({
                "code": -1002,
                "msg": "评论不存在",
            })
        except Exception as e:
            return JsonResponse({
                "code": -1000,
                "msg": f"删除失败: {str(e)}",
            })




def add_comment(request):
    # 添加登录验证
    if not request.user.is_authenticated:
        return JsonResponse({
            'code': -1001,
            'msg': '请先登录再评论'
        })
        
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            try:
                # 使用当前登录用户，而不是从POST数据中获取
                user = request.user
                
                # 获取文章ID并验证
                article_id = request.POST.get('article')
                if not article_id:
                    return JsonResponse({'code': -1002, 'msg': '文章ID不能为空'})
                
                article = get_object_or_404(Article, id=article_id)
                
                # 处理评论内容
                content = form.cleaned_data.get('content')
                if not content or content.strip() == '':
                    return JsonResponse({'code': -1003, 'msg': '评论内容不能为空'})
                
                # 处理父评论
                parent = None
                parent_id = request.POST.get('parent')
                if parent_id:
                    try:
                        parent = Comment.objects.get(id=parent_id, article=article)
                    except Comment.DoesNotExist:
                        return JsonResponse({'code': -1004, 'msg': '父评论不存在'})
                
                # 创建评论
                instance = Comment.objects.create(
                    user=user,
                    article=article,
                    content=content,
                    parent=parent
                )
                
                # 构建返回数据
                response_data = {
                    'code': 0,
                    'msg': '添加评论成功',
                    'data': {
                        "id": instance.id,
                        "content": instance.content,
                        "username": user.username,
                        "head": user.head.url if user.head else '',
                        "parent_username": instance.parent.user.username if instance.parent else None,
                        "create_time": instance.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    }
                }
                return JsonResponse(response_data)
                
            except Article.DoesNotExist:
                return JsonResponse({'code': -1005, 'msg': '文章不存在'})
            except Exception as e:
                return JsonResponse({'code': -1000, 'msg': f'评论失败: {str(e)}'})
        else:
            # 返回表单验证错误
            error_messages = []
            for field, errors in form.errors.items():
                for error in errors:
                    error_messages.append(f"{field}: {error}")
            return JsonResponse({
                'code': -1006,
                'msg': '表单验证失败',
                'errors': error_messages
            })
